package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-19 14:40
 **/
public class LeetCode151 {

    /**
     * 经过优化的代码
     * @param s
     * @return
     */
    public String reverseWords2(String s) {
        String str = s.trim();
        //根据空格(一个空格，多个空格，tab制表符)分隔字符串
        String[] s1 = str.split("\\s+");
        int low = 0;
        int high = s1.length - 1;
        while (low < high) {
            String temp = s1[low];
            s1[low] = s1[high];
            s1[high] = temp;
            low++;
            high--;
        }
        StringBuilder builder = new StringBuilder("");
        for (int i = 0; i < s1.length; i++) {
            if (i == s1.length - 1) {
                builder.append(s1[i]);
                break;
            }
            builder.append(s1[i] + " ");
        }

        return builder.toString();
    }

    public String reverseWords3(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> list = Arrays.asList(s.split("\\s+"));
        Collections.reverse(list);
        return String.join(" ", list);
    }

    public String reverseWords(String s) {
        s = removeBlank(s);
        StringBuilder res = new  StringBuilder();
        int len = s.length();
        int i = len - 1;
        int j = i;
        while (i >= 0) {
            while (i >= 0 && s.charAt(i) != ' ') {
                i--;
            }
            res.append(s.substring(i + 1, j + 1)).append(" ");
            while (i >= 0 && s.charAt(i) == ' ') {
                i--;
            }
            j=i;
        }

        //由于上面最后一次添加会多一个空格，所以去除字符串左右的空格
        return removeBlank(res.toString());

    }

    private String removeBlank(String s){
        int low = 0;
        int high = s.length() - 1;
        while (s.charAt(low) == ' ') {
            low++;
        }
        while (s.charAt(high) == ' ') {
            high--;
        }
        return s.substring(low, high + 1);
    }

}
